import { useCallback, useEffect, useState } from 'react';
import { getItem } from '@/services/aqchain-antd/item';
import { Contracts } from '@/app';
import { request } from 'umi';

export type Sale = {
  seller: string;
  price: number;
  buyer: string;
};

export type Auction = {
  seller: string;
  lowestPrice: number;
  end: number;
  highestBidder: string;
  highestBid: number;
};

export type ItemState = {
  item: API.ModelsItem | undefined;
  tokenId: number;
  owner: string;
  approved: string;
  sale: Sale | undefined;
  auction: Auction | undefined;
  loading: boolean;
  error: Error | undefined;
};
const initialItemState = {
  item: undefined,
  tokenId: 0,
  owner: '',
  approved: '',
  sale: undefined,
  auction: undefined,
  loading: true,
  error: undefined as Error | undefined,
};

export default () => {
  const [state, setState] = useState<ItemState>(initialItemState);
  const [responsive, setResponsive] = useState<boolean>(false);

  // 获取作品相关信息
  const getItemState = useCallback(
    async (fileHash: string, contracts: Contracts) => {
      // 设置初始状态
      setState((s) => ({ ...s, loading: true, error: undefined }));
      try {
        // 查询链上信息
        const tokenId = await contracts.fileStorageContract?.getTokenId(
          fileHash,
        );
        const tokenURI = await contracts.fileStorageContract?.tokenURI(tokenId);
        // 获取链下存储信息
        const { data } = await request<API.ModelsItemResponse>(tokenURI, {
          method: 'GET',
        });
        // 获取当前token拥有者地址
        let owner = await contracts.fileStorageContract?.ownerOf(tokenId);
        // 获取当前token已授权账户地址
        const approved = await contracts.fileStorageContract?.getApproved(
          tokenId,
        );
        // 如果当前token所有者为定价交易合约 获取定价交易的具体信息
        if (owner == contracts.saleContract.address) {
          const sale: Sale = {
            seller: await contracts.saleContract.getSaller(tokenId),
            price: await contracts.saleContract.getPrice(tokenId),
            buyer: await contracts.saleContract.getBuyer(tokenId),
          };
          setState((s) => ({ ...s, sale: sale }));
        }

        // 如果当前token所有者为拍卖交易合约 获取拍卖交易的具体信息
        if (owner == contracts.auctionContract.address) {
          const auction: Auction = {
            seller: await contracts.auctionContract.getSeller(tokenId),
            lowestPrice: await contracts.auctionContract.getLowestPrice(
              tokenId,
            ),
            end: await contracts.auctionContract.getEnd(tokenId),
            highestBidder: await contracts.auctionContract.getHighestBidder(
              tokenId,
            ),
            highestBid: await contracts.auctionContract.getHighestBid(tokenId),
          };

          console.log(
            await contracts.auctionContract.getHighestBidder(tokenId),
          );

          console.log(owner);
          console.log(auction);

          setState((s) => ({ ...s, auction: auction }));
        }

        setState((s) => ({
          ...s,
          item: data,
          tokenId: tokenId,
          owner: owner.toString(),
          approved: approved.toString(),
          loading: false,
        }));
      } catch (e) {
        // 设置错误状态
        console.error(e);
        setState((s) => ({ ...s, error: e, loading: false }));
      }
    },
    [],
  );

  // 获取
  // const refresh = useCallback(async() => {
  //   setState(s => ({ ...s,loading: true, error: undefined }))
  //   try {
  //     const fileHash = state.fileHash
  //     if(!fileHash){
  //       throw new Error('未初始化 fileHash')
  //     }
  //     const { data } = await getItem({fileHash})
  //     console.log(data)
  //     setState(s => ({ ...s, item: data, loading: false }));
  //   } catch(e) {
  //     setState(s => ({ ...s, error: e, loading: false }));
  //   }
  // }, []);

  const setInitialState = useCallback((initialState) => {
    setState((s) => ({ ...s, initialState, loading: false }));
  }, []);

  return {
    ...state,
    getItemState,
    setInitialState,
    responsive,
    setResponsive,
  };
};
